define(['zepto', 'butterfly/view','../../bsl',
    'text!./share.html'
], function($, View, bsl, share) {
    var me = null;

    var view = View.extend({
        events: {
            "tap #back":"back",
            "tap #openDoc":"OpenDoc",

            "tap #shareCameraPicture":"shareCameraPicture",
            "tap #shareGalleryPicture":"shareGalleryPicture",
            "tap #shareLogoPicture":"shareLogoPicture",
            "tap #shareShow":"shareShow",
            "tap #shareSystem":"shareSystem",
            "tap #sharehref":"sharehref",
            "tap #sharehrefTitle":"sharehrefTitle",
            "tap #sharehrefDes":"sharehrefDes",
            "tap #shareHref":"shareHref",
            "tap #cancelAuth":"cancelAuth",
           
        },
        render: function() {
            me = this;
        },

        onShow: function() {

            if(window.bsl){
                bslReady();
            }else{
                document.addEventListener("bslready",bslReady,false);
            };// 绑定自定义事件 滑动切换日历等           


        },
        shares:null,
        bhref:false,
        Intent:null,
        File:null,
        Uri:null,
        main:null,
        // H5 bsl事件处理
        bslReady: function(){
            updateSerivces();
            if(bsl.os.name=="Android"){
                me.Intent = bsl.android.importClass("android.content.Intent");
                me.File = bsl.android.importClass("java.io.File");
                me.Uri = bsl.android.importClass("android.net.Uri");
                me.main = bsl.android.runtimeMainActivity();
            }
        },

        
        /**
         * 更新分享服务
         */
        updateSerivces: function(){
            bsl.share.getServices( function(s){
                shares={};
                for(var i in s){
                    var t=s[i];
                    shares[t.id]=t;
                }
            }, function(e){
                console.info( "获取分享服务列表失败："+e.message );
            } );
        },
        /**,
         * 调用系统分享
         * 调用
         */
        shareSystem: function() {
            if(bsl.os.name!=="Android"){
                bsl.nativeUI.alert("此平台暂不支持系统分享功能!");
                return;
            }
            var intent=new Intent(Intent.ACTION_SEND);
            var p = "";
            if(pic&&pic.realUrl){
                p = pic.realUrl;
                if(p.substr(0,7)==="file://"){
                    p=p.substr(7);
                }else if(p.sub(0)!=="/"){
                    p=bsl.io.convertLocalFileSystemURL(p);
                }
            }
            var f = new File(p);
            var uri = Uri.fromFile(f);
            if(f.exists()&&f.isFile()){
                console.log("images/*");
                intent.setType("images/*");
                intent.putExtra(Intent.EXTRA_STREAM,uri);
            }else{
                console.log("text/plain");
                intent.setType("text/plain");
            }
            intent.putExtra(Intent.EXTRA_SUBJECT,"HBuilder");
            intent.putExtra(Intent.EXTRA_TEXT,sharecontent.value);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            main.startActivity(Intent.createChooser(intent,"系统分享"));
        },
        /**
           * 分享操作
           * @param {String} id
           */
        shareAction: function(id,ex) {
            var s=null;
            console.info( "分享操作：" );
            if(!id||!(s=shares[id])){
                console.info( "无效的分享服务！" );
                return;
            }
            if ( s.authenticated ) {
                console.info( "---已授权---" );
                shareMessage(s,ex);
            } else {
                console.info( "---未授权---" );
                s.authorize( function(){
                        shareMessage(s,ex);
                    },function(e){
                    console.info( "认证授权失败："+e.code+" - "+e.message );
                });
            }
        },
        /**
           * 发送分享消息
           * @param {bsl.share.ShareService} s
           */
        shareMessage: function(s,ex){
            var msg={content:sharecontent.value,extra:{scene:ex}};
            if(bhref){
                msg.href=sharehref.value;
                if(sharehrefTitle&&sharehrefTitle.value!=""){
                    msg.title=sharehrefTitle.value;
                }
                if(sharehrefDes&&sharehrefDes.value!=""){
                    msg.content=sharehrefDes.value;
                }
                msg.thumbs=["_www/logo.png"];
                msg.pictures=["_www/logo.png"];
            }else{
                if(pic&&pic.realUrl){
                    msg.pictures=[pic.realUrl];
                }
            }
            console.info(JSON.stringify(msg));
            s.send( msg, function(){
                console.info( "分享到\""+s.description+"\"成功！ " );
            }, function(e){
                console.info( "分享到\""+s.description+"\"失败: "+e.code+" - "+e.message );
            } );
        },
        /**
         * 解除所有分享服务的授权
         */
        cancelAuth: function(){try{
            console.info( "解除授权：" );
            for ( var i in shares ) {
                var s = shares[i];
                if ( s.authenticated ) {
                    console.info( "取消\""+s.description+"\"");
                }
                s.forbid();
            }
            // 取消授权后需要更新服务列表
            updateSerivces();
            console.info( "操作成功！" );}catch(e){alert(e);}
        },
        // 拍照添加图片分享
        shareCameraPicture: function(){
            console.info("拍照添加分享图片：");
            var cmr=bsl.camera.getCamera();
            cmr.captureImage(function(p){
                bsl.io.resolveLocalFileSystemURL(p,function(entry){
                    pic.src=entry.toLocalURL();
                    pic.realUrl=p;
                    console.info("拍照图片："+pic.realUrl);
                },function(e){
                    console.info("读取拍照文件错误："+e.message);
                } );
            },function(e){
                console.info( "拍照失败："+e.message );
            });
        },
        // 从相册添加图片分享
        shareGalleryPicture: function(){
            console.info("从相册添加分享图片：");
            bsl.gallery.pick(function(p){
                // 从相册返回的路径不需要转换可以直接使用
                pic.src=p;
                pic.realUrl=pic.src;
                console.info("选择图片："+pic.realUrl);
        //      bsl.io.resolveLocalFileSystemURL(p,function(entry){
        //          pic.src=entry.toLocalURL();
        //          pic.realUrl=pic.src;
        //          console.info("选择图片："+pic.realUrl);
        //      },function(e){
        //          console.info("读取拍照文件错误："+e.message);
        //      } );
            });
        },
        // 使用Logo图片分享
        shareLogoPicture: function(){
            console.info("使用Logo分享图片：");
            var url="_www/logo.png";
            bsl.io.resolveLocalFileSystemURL(url,function(entry){
                pic.src=entry.toLocalURL();
                pic.realUrl=url;
            },function(e){
                console.info("读取Logo文件错误："+e.message);
            } );
        },
        // 打开分享
        shareShow: function(){
            bhref=false;
            var ids=[{id:"weixin",ex:"WXSceneSession"},{id:"weixin",ex:"WXSceneTimeline"},{id:"sinaweibo"},{id:"tencentweibo"}],
            bts=[{title:"发送给微信好友"},{title:"分享到微信朋友圈"},{title:"分享到新浪微博"},{title:"分享到腾讯微博"}];
            if(bsl.os.name=="iOS"){
                ids.push({id:"qq"});
                bts.push({title:"分享到QQ"});
            }
            bsl.nativeUI.actionSheet({cancel:"取消",buttons:bts},
                function(e){
                    var i=e.index;
                    if(i>0){
                        shareAction(ids[i-1].id,ids[i-1].ex);
                    }
                }
            );
        },
        // 分析链接
        shareHref: function(){
            bhref=true;
            var ids=[{id:"weixin",ex:"WXSceneSession"},{id:"weixin",ex:"WXSceneTimeline"},{id:"qq"}],
            bts=[{title:"发送给微信好友"},{title:"分享到微信朋友圈"},{title:"分享到QQ"}];
            bsl.nativeUI.actionSheet({cancel:"取消",buttons:bts},
                function(e){
                    var i=e.index;
                    if(i>0){
                        shareAction(ids[i-1].id,ids[i-1].ex);
                    }
                }
            );
        },

        back: function(e){
            window.history.go(-1);
        },

        OpenDoc : function(e){
           
            window.butterfly.navigate('com.no5.cordovademo/doc/share', {
                trigger: true
            });
        },
    });
    return view;
});
